/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.groupcash.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.group.entity.Group;
import com.jeeplus.modules.group.service.GroupService;
import com.jeeplus.modules.groupcash.entity.GroupCash;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.cashprop.entity.CashProp;
import com.jeeplus.modules.cashprop.service.CashPropService;
import com.jeeplus.modules.groupcash.service.GroupCashService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 团长提现Controller
 * @author lixinapp
 * @version 2019-10-14
 */
@Controller
@RequestMapping(value = "${adminPath}/groupcash/groupCash")
public class GroupCashController extends BaseController {

	@Autowired
	private GroupCashService groupCashService;
//	@Autowired
	private GroupService groupService;
	@Autowired
	private CashPropService cashPropService;

	@ModelAttribute
	public GroupCash get(@RequestParam(required=false) String id) {
		GroupCash entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = groupCashService.get(id);
		}
		if (entity == null){
			entity = new GroupCash();
		}
		return entity;
	}

	/**
	 * 团长提现列表页面
	 */
	@RequiresPermissions("groupcash:groupCash:list")
	@RequestMapping(value = {"list", ""})
	public String list(GroupCash groupCash, Model model) {
		model.addAttribute("groupCash", groupCash);
		return "modules/groupcash/groupCashList";
	}

	/**
	 * 团长提现列表数据
	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(GroupCash groupCash, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断当前登录用户
		User user = UserUtils.getUser();
//		if (user.isShop()) {
//			groupCash.setDataScope(" AND group.user_id = '"+user.getId()+"' ");
//		}
		Page<GroupCash> page = groupCashService.findPage(new Page<GroupCash>(request, response), groupCash);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑团长提现表单页面
	 */
	@RequiresPermissions(value={"groupcash:groupCash:view","groupcash:groupCash:add","groupcash:groupCash:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(GroupCash groupCash, Model model) {
		String balance = "0";
		// 判断当前登录用户
		model.addAttribute("balance", balance);
		model.addAttribute("groupCash", groupCash);
		return "modules/groupcash/storeCashForm";
	}

	/**
	 * 保存团长提现
	 */
	@ResponseBody
	@RequiresPermissions(value={"groupcash:groupCash:add","groupcash:groupCash:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(GroupCash groupCash, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		if (StringUtils.isBlank(groupCash.getId())) {
			User user = UserUtils.getUser();
//			if (user.isShop()) {
			Group group = groupService.findUniqueByProperty("user_id", user.getId());
			if (new BigDecimal(groupCash.getAmount()).compareTo(new BigDecimal(group.getBalance())) > 0) {
				j.setSuccess(false);
				j.setMsg("可用余额不足");
				return j;
			}
//			}
				// 手续费
				BigDecimal prop = BigDecimal.ZERO;

				List<CashProp> propList = cashPropService.findList(new CashProp());
				for (CashProp cashProp : propList) {
					if ("1".equals(cashProp.getType())) {
						prop = new BigDecimal(cashProp.getProp());
						break;
					}
				}

//				groupCash.setStore(group);
				groupCash.setState("0");

				/**
				 * 后台hibernate-validation插件校验
				 */
				String errMsg = beanValidator(groupCash);
				if (StringUtils.isNotBlank(errMsg)){
					j.setSuccess(false);
					j.setMsg(errMsg);
					return j;
				}
				groupCash.setFee(prop.multiply(new BigDecimal(groupCash.getAmount())).toString());
				groupCashService.add(groupCash);
			}

		j.setSuccess(true);
		j.setMsg("申请提现成功");
		return j;
	}


	/**
	 * 审核团长提现
	 */
	@ResponseBody
	@RequiresPermissions(value="groupcash:groupCash:edit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(GroupCash groupCash, String type) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!"0".equals(groupCash.getState())) {
			j.setSuccess(false);
			j.setMsg("只能操作待审核的申请");
			return j;
		}
		groupCash.setState(type);
		groupCash.setAuditDate(new Date());
		groupCashService.audit(groupCash);
		j.setSuccess(true);
		j.setMsg("审核团长提现成功");
		return j;
	}

	/**
	 * 删除团长提现
	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(GroupCash groupCash) {
		AjaxJson j = new AjaxJson();
		groupCashService.delete(groupCash);
		j.setMsg("删除团长提现成功");
		return j;
	}

	/**
	 * 批量删除团长提现
	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			groupCashService.delete(groupCashService.get(id));
		}
		j.setMsg("删除团长提现成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:export")
	@RequestMapping(value = "export")
	public AjaxJson exportFile(GroupCash groupCash, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "团长提现"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<GroupCash> page = groupCashService.findPage(new Page<GroupCash>(request, response, -1), groupCash);
			new ExportExcel("团长提现", GroupCash.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出团长提现记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:import")
	@RequestMapping(value = "import")
	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<GroupCash> list = ei.getDataList(GroupCash.class);
			for (GroupCash groupCash : list){
				try{
					groupCashService.save(groupCash);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条团长提现记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条团长提现记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入团长提现失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 下载导入团长提现数据模板
	 */
	@ResponseBody
	@RequiresPermissions("groupcash:groupCash:import")
	@RequestMapping(value = "import/template")
	public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "团长提现数据导入模板.xlsx";
			List<GroupCash> list = Lists.newArrayList();
			new ExportExcel("团长提现数据", GroupCash.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
	}

}